package com.iwop.moto.controller.weixin;

import com.alibaba.fastjson.JSON;
import com.iwop.moto.auth.LoginAuth;
import com.iwop.moto.comm.Comm;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.controller.BaseController;
import com.iwop.moto.model.ResultModel;
import com.iwop.moto.model.SMS;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.model.User;
import com.iwop.moto.service.*;
import com.iwop.moto.utils.api.YunXin.YunXinUtils;
import com.iwop.moto.utils.encrypt.MD5Util;
import com.iwop.moto.utils.file.FileUtil;
import com.iwop.moto.utils.http.SessionUtils;
import com.iwop.moto.utils.stringUtil.*;
import com.iwop.moto.utils.weixin.SendModelMsg;
import com.iwop.moto.utils.weixin.WeixinUtil;
import com.iwop.moto.utils.weixin.model.WxPayDto;
import com.iwop.moto.utils.weixin.utils.WxPayUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @模块 微信[服务商/维修店]加盟
 * @日期 liuwb 2016-08-18 15:04 by create
 * @explain :
 */
@Controller
public class WxUserController extends BaseController {

    @Autowired
    private IDataService dataService;

    @Autowired
    private UserService userService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private PromotionService promotionService;

    @Autowired
    private AuditHistoryService auditHistoryService;

    @Autowired
    private SMSService smsService;

    @Autowired
    private DistrictService districeService;

    @Autowired
    private TeamMemberService teamMemberService;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private FCouponService fCouponService;
    @Autowired
    private YunxinService yunxinService;

    Logger logger=Logger.getLogger(WxUserController.class);
    /**
     * @功能: 合作加盟
     * @日期: liuwb by 2016-09-10 on create
     */
    @RequestMapping(value="/api/wx/league/main")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxLeagueMain() {
        SuperRecordModel SRModel = this.getSRModel();
        ModelAndView mv = new ModelAndView();
        try {
            mv.addObject("ticket",getWxTicket().get("ticket"));
            mv.addObject("wx_appid",Comm.APPID);
            mv.addObject("SRModel",SRModel);
            mv.setViewName("weixin/guide");
        } catch (Exception e){
            e.printStackTrace();
            return errorMv("获取微信Ticket失败");
        }
        return mv;
    }

    /**
     * @功能: 加盟服务商 - 跳转页面
     * @日期: liuwb 2016-08-18 15:09 by create
     */
    @RequestMapping(value="/api/wx/service/league")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxServiceLeague() {
        SuperRecordModel SRModel = this.getSRModel();
        ModelAndView mv = new ModelAndView();
        try{
            SuperRecordModel wxInfo = (SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
            if(wxInfo != null){
                wxInfo.put("wx_open_id",wxInfo.getString("openid"));
                wxInfo.put("user_type","5");//[5:服务商]
                SuperRecordModel userInfo = userService.findUserByOpenId(wxInfo);
                if(userInfo != null && userInfo.getString("audit_flag").equals("2")){//已经注册过并且审核通过
                   return apiWxUserMembersCenter();
                } else if(userInfo != null ){// 其他审核状态
                    mv.addObject("register",true);// 在审核中
                    mv.addObject("serviceInfo", userInfo);
                    SuperRecordModel payParams = new SuperRecordModel();
                    payParams.put("pay_type","bargain");//预定金交付金额
                    payParams.put("user_id",userInfo.get("sid"));
                    payParams.put("wx_open_id",userInfo.get("wx_open_id"));
                    Long payCount = wxPayService.findByParamsCount(payParams);
                    mv.addObject("payCount",payCount.intValue());
                    if("".equals(SRModel.getString("promotionCode"))){//如果新的推广码不存在 默认获取原有
                        SRModel.put("fromUser",userInfo.getString("sid"));
                        List<SuperRecordModel> proList = promotionService.findPromotionByParams(SRModel);
                        if(proList!=null && proList.size()>0){
                            SRModel.put("promotionCode",proList.get(0).get("promotion_code"));
                        }
                    }
                }
            }
            if(!"".equals(SRModel.getString("promotionCode"))){
                SuperRecordModel promotionUserInfo = userService.findUserByPromotionCode(SRModel.getString("promotionCode"));
                if(promotionUserInfo!=null){
                    SuperRecordModel promotion = new SuperRecordModel();
                    promotion.put("code",SRModel.getString("promotionCode"));
                    promotion.put("userType",promotionUserInfo.getString("user_type"));
                    promotion.put("serviceName",StringUtils.repname(promotionUserInfo.getString("nickname")));
                    promotion.put("serviceTel", StringUtils.repmobile(promotionUserInfo.getString("tel")));
                    mv.addObject("promotion",promotion);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        mv.setViewName("weixin/service_enter");
        return mv;
    }



    /**
     * @功能: 加盟维修店 - 跳转页面
     * @日期: liuwb  2016-08-20 15:29 by create
     * @参数: promotionCode 推广码 (推广)
     */
    @RequestMapping(value="/api/wx/store/league")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxStoreLeague() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel SRModel = this.getSRModel();
       // SRModel.put("promotionCode","rpVfZ2BT");//测试用
        try {
            SuperRecordModel wxInfo = (SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
            if(wxInfo != null){
                wxInfo.put("wx_open_id",wxInfo.getString("openid"));
                wxInfo.put("user_type","1");//[1:维修店]
                SuperRecordModel userInfo = userService.findUserByOpenId(wxInfo);
                if(userInfo != null ){
                    mv.addObject("userInfo",userInfo);
                    SRModel.put("user_id",userInfo.getString("sid"));
                    mv.addObject("storeInfo",storeService.findStoreByUserId(SRModel));
                    if("".equals(SRModel.getString("promotionCode"))){//如果新的推广码不存在 默认获取原有
                        SRModel.put("fromUser",userInfo.getString("sid"));
                        List<SuperRecordModel> proList = promotionService.findPromotionByParams(SRModel);
                        if(proList!=null && proList.size()>0){
                            SRModel.put("promotionCode",proList.get(0).get("promotion_code"));
                        }
                    }
                }
            }
            if(!"".equals(SRModel.getString("promotionCode"))){
                SuperRecordModel promotionUserInfo =  userService.findUserByPromotionCode(SRModel.getString("promotionCode"));
                if(promotionUserInfo!=null){
                    SuperRecordModel promotion = new SuperRecordModel();
                    promotion.put("code",SRModel.getString("promotionCode"));
                    promotion.put("userType",promotionUserInfo.getString("user_type"));
                    promotion.put("serviceName",StringUtils.repname(promotionUserInfo.getString("nickname")));
                    promotion.put("serviceTel", StringUtils.repmobile(promotionUserInfo.getString("tel")));
                    mv.addObject("promotion",promotion);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        mv.setViewName("weixin/store_enter");
        return mv;
    }

    /**
     * @功能: 加盟服务商 - 保存
     * @日期: liuwb 2016-08-18 15:33 by create
     * @参数: readname 真实姓名
     * @参数: tel 手机号
     * @参数: province 省
     * @参数: city 市
     * @参数: area 区
     * @参数: address 详细地址
     */
    @RequestMapping(value="/api/wx/service/save")
    @ResponseBody
    @LoginAuth(isWx = true)
    public ResultModel apiWxServiceSave() {
        SuperRecordModel srm = this.getSRModel();
        try{
            SMS sms = new SMS();
            sms.setTel(srm.getString("tel"));
            sms.setContent(srm.getString("code"));
            sms = smsService.findCheckCodeByTel(sms);
            Long nowTime = new Date().getTime();//当前时间毫秒
            if(sms == null){
                return getErr(ErrCode.ERROR_SMS);
            } else if(sms.getStatus() == null || "1".equals(sms.getStatus())){
                return getErr(ErrCode.ERROR_SMS_USED);
            }
            Long smsTime = sms.getAddtime().getTime();
            if(nowTime > (smsTime + (300 * 1000)) ){//判断是否5分钟之内
                return getErr(ErrCode.ERROR_SMS_OVERDUE);
            }
            boolean isCreate = "".equals(srm.getString("sid").trim());
            String promotionCode = srm.getString("promotion_code");
            SuperRecordModel prUser = new SuperRecordModel();
            if(!"".equals(promotionCode)){
                prUser = userService.findUserByPromotionCode(promotionCode);
            }
            if(prUser != null&&prUser.get("sid")!=null  && "true".equals(srm.getString("valBtn")) &&
                    !"5".equals(prUser.getString("user_type"))){// 如果不是服务商推荐
                return getErr(ErrCode.PROMOTION_CODE_INVAILD_STORE);
            }
            if("4".equals(srm.getString("level")) && "".equals(srm.getString("town").trim())){//level=4的服务商如果有第四级必须选择(根据区/县) 直辖市没有则除外
                SuperRecordModel district = new SuperRecordModel();
                district.put("param_upid",srm.getString("area").trim());
                List<SuperRecordModel> lists = districeService.findDistrictByParam(district);
                if(lists!=null && lists.size()>0){
                    return getErr(ErrCode.CHOICE_TOWN);
                }
            }
            SuperRecordModel wxInfo = (SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
            SuperRecordModel userSrm = new SuperRecordModel();
            userSrm.put("wx_open_id", wxInfo.getString("openid"));//微信唯一标识
            userSrm.put("imgpath", FileUtil.downWxImgUrl(wxInfo.getString("headimgurl")));//微信头像
            userSrm.put("username",srm.getString("tel"));
            userSrm.put("tel",srm.getString("tel"));
            userSrm.put("level",srm.get("level"));//
            userSrm.put("nickname",srm.getString("readname"));
            userSrm.put("province",srm.getString("province"));
            userSrm.put("city",srm.getString("city"));
            userSrm.put("area",srm.getString("area"));
            userSrm.put("town",srm.getString("town"));
            userSrm.put("address",srm.getString("address"));
            userSrm.put("audit_flag","0");
            userSrm.put("audit_time",new Date());
            if("".equals(srm.getString("sid").trim())){
                srm.put("userType","5");
                boolean telBl = userService.checkUserByTel(srm);
                if(!telBl){
                    return getErr(ErrCode.USER_ERROR_TELEXST);
                }
                userSrm.put("sid", ObjectId.userUUID());
                userSrm.put("user_type","5");// 5:服务商
                userSrm.put("promotion_code", StringUtils.getPromotionCode("5", srm.getString("tel")));//生成推广码
                //userSrm.put("pwd", MD5Util.MD5Encode(userSrm.getString("promotion_code"),""));
                //userSrm.put("paypwd", MD5Util.MD5Encode(userSrm.getString("promotion_code"),""));
                userSrm.put("create_time", new Date());
                userService.insertUser(userSrm);
            } else {
                userSrm.put("sid",srm.getString("sid"));
                userService.updateUser(userSrm);
                srm.put("from_user",srm.getString("sid"));
                promotionService.deleteByFromUser(srm);//删除原来关联关系
            }
            if(prUser != null && prUser.get("sid")!=null && !"".equals(promotionCode.trim())
                    && "true".equals(srm.getString("valBtn"))){// 并且选择推荐服务商
                SuperRecordModel promotionSrm = new SuperRecordModel();
                promotionSrm.put("sid",ObjectId.userUUID());
                promotionSrm.put("host_user",prUser.getString("sid"));
                promotionSrm.put("promotion_code",promotionCode);
                promotionSrm.put("from_user",userSrm.getString("sid"));
                promotionSrm.put("status_flag","1");
                promotionSrm.put("status_time",new Date());
                promotionService.insertPromotion(promotionSrm);
            }
            /** 审核历史记录 **/
            SuperRecordModel auditSrm = new SuperRecordModel();
            auditSrm.putAll(userSrm);
            auditSrm.put("isCreate",isCreate);
            auditHistoryService.inserServiceAuditHistory(auditSrm);
            /** 标识验证码已被使用 **/
            sms.setStatus("1");
            smsService.save(sms);
            return getSucceed(ErrCode.SUCCEED);
        }catch (Exception e){
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * @功能 加盟维修店 - 保存
     * @日期 liuwb 2016-08-19 20:25 by create
     */
    @RequestMapping(value="/api/wx/store/save")
    @ResponseBody
    @LoginAuth(isWx = true)
    public ResultModel apiWxStoreSave() {
        // 请求中的参数
        SuperRecordModel srm = this.getSRModel();
        try{
            SMS sms = new SMS();
            sms.setTel(srm.getString("tel"));
            sms.setContent(srm.getString("code"));
            sms = smsService.findCheckCodeByTel(sms);
            Long nowTime = new Date().getTime();//当前时间毫秒
            if(sms == null){
                return getErr(ErrCode.ERROR_SMS);
            } else if(sms.getStatus() == null || "1".equals(sms.getStatus())){
                return getErr(ErrCode.ERROR_SMS_USED);
            }
            Long smsTime = sms.getAddtime().getTime();
            if(nowTime > (smsTime + (300 * 1000)) ){//判断是否5分钟之内
                return getErr(ErrCode.ERROR_SMS_OVERDUE);
            }
            boolean isCreate = "".equals(srm.getString("sid").trim());//没有主键,标识为新增(true)
            // 微信用户信息
            SuperRecordModel wxInfo = (SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
            String promotionCode = srm.getString("promotion_code");
            SuperRecordModel prUser = new SuperRecordModel();
            if(!"".equals(promotionCode)){
                prUser = userService.findUserByPromotionCode(promotionCode);
            }
            if(( prUser == null || prUser.get("sid")==null )  && "true".equals(srm.getString("valBtn"))){// 判断是否推广码是否有效
                return getErr(ErrCode.PROMOTION_CODE_INVAILD);
            }
            if("".equals(srm.getString("town").trim())){//维修店地址如果有第四级必须选择(根据区/县) 直辖市没有则除外
                SuperRecordModel district = new SuperRecordModel();
                district.put("param_upid",srm.getString("area").trim());
                List<SuperRecordModel> lists = districeService.findDistrictByParam(district);
                if(lists!=null && lists.size()>0){
                    return getErr(ErrCode.CHOICE_TOWN);
                }
            }
            SuperRecordModel store = new SuperRecordModel();// 店铺信息Model
            SuperRecordModel userSrm = new SuperRecordModel();// 用户信息Model
            userSrm.put("wx_open_id", wxInfo.getString("openid"));//微信唯一标识
            userSrm.put("imgpath", FileUtil.downWxImgUrl(wxInfo.getString("headimgurl")));//微信头像
            userSrm.put("username",srm.getString("tel"));
            userSrm.put("user_type","1");// 1:维修店
            userSrm.put("tel",srm.getString("tel"));
            userSrm.put("contacts",srm.getString("contacts"));
            userSrm.put("nickname",srm.getString("readname"));
            userSrm.put("province",srm.getString("province"));
            userSrm.put("city",srm.getString("city"));
            userSrm.put("town",srm.getString("town"));
            userSrm.put("area",srm.getString("area"));
            userSrm.put("address",srm.getString("address"));
            if(userService.findServiceCountByDistrict(userSrm)==0){
                userSrm.put("audit_flag","1" );//没有服务商默认平台审核 获取 平台拒绝重新提交审核
            }else{
                userSrm.put("audit_flag","0" );//有服务商默认服务商审核
            }
            userSrm.put("audit_time",new Date());
            // 店铺信息
            store.put("operator",srm.getString("operator"));//经营者
            store.put("regname",srm.getString("regname"));//营业执号
            store.put("certpath",srm.getString("certpath"));//营业执照

            store.put("cardno",srm.getString("cardno"));//身份证号
            store.put("frontpath",srm.getString("frontpath"));//身份证正面
            store.put("sidepath",srm.getString("sidepath"));//身份证反面

            store.put("storename",srm.getString("storename"));//店铺名称
            store.put("realname",srm.getString("readname"));//真实姓名
            store.put("address",srm.getString("address"));//店铺地址
            store.put("contacts",srm.getString("contacts"));//联系人
            store.put("tel1",srm.getString("storeTel"));//联系人电话

            store.put("storelevel",1);//店铺等级
            store.put("addtime",new Date());//添加时间
            store.put("status","0");//0:未审核
            try {
                if(isCreate){//新增
                    srm.put("userType","1");
                    boolean telBl = userService.checkUserByTel(srm);
                    if(!telBl){
                        return getErr(ErrCode.USER_ERROR_TELEXST);
                    }
                    userSrm.put("sid", ObjectId.userUUID());
                    userSrm.put("promotion_code", StringUtils.getPromotionCode("1", srm.getString("tel")));//生成推广码
                   // userSrm.put("pwd", MD5Util.MD5Encode(userSrm.getString("promotion_code"),""));
                   // userSrm.put("paypwd", userSrm.getString("pwd"));
                    userSrm.put("create_time", new Date());
                    String serial = SequenceUtil.Serial();
                    userSrm.put("pwd",  MD5Util.MD5Encode(serial, "UTF-8"));
                    if(StringUtils.isEmpty(promotionCode)){
                        userSrm.put("new_user","old");
                    }else {
                        userSrm.put("new_user","new");
                    }
                    userService.insertUser(userSrm);//保存用户信息
                    store.put("sid",ObjectId.storeUUID());
                    store.put("user_id",userSrm.getString("sid"));//关联的用户ID
                    storeService.save(store);
                }else{//修改
                    userSrm.put("sid", srm.getString("sid"));
                    userService.updateUser(userSrm);//修改用户信息
                    store.put("user_id",srm.getString("sid"));
                    if(storeService.findStoreByUserId(store)!=null){//维修店存在
                        storeService.updateByUserId(store);//更新维修店信息
                    }else{//否则新增
                        store.put("sid",ObjectId.storeUUID());
                        store.put("user_id",userSrm.getString("sid"));//关联的用户ID
                        storeService.save(store);
                    }
                    srm.put("from_user",srm.getString("sid"));
                    promotionService.deleteByFromUser(srm);//删除原来关联关系
                    SuperRecordModel delAuditParam = new SuperRecordModel();
                    delAuditParam.put("audit_fkey",srm.getString("sid"));
                    delAuditParam.put("audit_type","Moto");
                    delAuditParam.put("audit_status","0");
                    auditHistoryService.deleteAuditByParam(delAuditParam);
                    teamMemberService.deleteTeamByFkey(srm.getString("sid"));//删除原来逻辑关系
                }
                if(prUser.get("sid")!=null && !"".equals(promotionCode.trim())
                        && "true".equals(srm.getString("valBtn"))){// 并且选择推荐服务商
                    SuperRecordModel promotionSrm = new SuperRecordModel();
                    promotionSrm.put("sid",ObjectId.userUUID());
                    promotionSrm.put("host_user",prUser.getString("sid"));
                    promotionSrm.put("promotion_code",promotionCode);
                    promotionSrm.put("from_user",userSrm.getString("sid"));
                    promotionSrm.put("status_flag","1");
                    promotionSrm.put("status_time",new Date());
                    promotionService.insertPromotion(promotionSrm);
                    String flag="new";
                    SessionUtils.setKeyValueString(userSrm.getString("sid") + "_new", flag);
                }else {
                    String flag="old";
                    SessionUtils.setKeyValueString(userSrm.getString("sid") + "_new", flag);
                }
            }catch (Exception e){
                e.printStackTrace();
                if(isCreate){//
                    Long countNum = storeService.findUserAndStoreKeyCount(store);
                    if(countNum.intValue()==0){//新增时异常引起的用户新增成功维修店失败,需删除用户数据
                        userService.delete(userSrm.getString("sid"));
                    }
                }
                return getErr(ErrCode.ERROR_SYSTEM);
            }
            /** 审核历史记录 **/
            SuperRecordModel auditSrm = new SuperRecordModel();
            auditSrm.putAll(userSrm);
            auditSrm.put("isCreate",isCreate);
            auditHistoryService.inserStoreAuditHistory(auditSrm);
            /** 标识验证码已被使用 **/
            sms.setStatus("1");
            smsService.save(sms);
            SuperRecordModel srms=new SuperRecordModel();
            srms.put("coupon_type","newStore");
            double random = Math.random();
            srms.put("random",random);
            List<SuperRecordModel> couponByTypes = fCouponService.getCouponByType(srms);
            for (SuperRecordModel couponByType : couponByTypes) {
                srm.put("sid",ObjectId.UUID());
                srm.put("user_id",userSrm.getString("sid"));
                srm.put("coupon_id",couponByType.getString("sid"));
                srm.put("withdrawals","0");
                srm.put("status_flag","1");
                srm.put("start_time", new Date());
                srm.put("end_time",couponByType.get("end_time"));
                srm.put("coupon_type", couponByType.get("coupon_type"));
                srm.put("c_time", new Date());
                fCouponService.insertUserCoupon(srm);
            }
            createIMUser(userSrm);
            return getSucceed(ErrCode.SUCCEED);
        }catch (Exception e){
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
       }
    }

    /**
     * 创建IM用户
     * */
    private boolean createIMUser(SuperRecordModel user){
        try{
            String token = SequenceUtil.Serial("S");
            String result = YunXinUtils.addIMUser(user.getString("sid"), user.getString("nickname"), user.getString("imgpath"), token);
            Map parse = (Map) JSON.parse(result);
            int code = (int)parse.get("code");
            if(code==200){
                SuperRecordModel srm=new SuperRecordModel();
                srm.put("im_accid",user.getString("sid"));
                srm.put("im_name",user.getString("nickname"));
                srm.put("im_icon", user.getString("imgpath"));
                srm.put("im_token",token);
                yunxinService.insertIM(srm);
                return true;
            }else{
                logger.error("云信注册返回错误结果：" + result);
                logger.error("云信注册时间：" + new Date());
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @功能: 校验手机号是否已经注册
     * @日期: liuwb on 2016-08-24 20:39 by create
     * @参数: tel 手机号
     * @参数: userType 用户类型
     */
    @RequestMapping(value="/ajax/wx/verify/tel")
    @ResponseBody
    public ResultModel ajaxWxVerifyTel() {
        SuperRecordModel SRModel = this.getSRModel();
        try {
            boolean telBl = userService.checkUserByTel(SRModel);
            if (telBl) {
               return getSucceed(ErrCode.SUCCEED);
            } else {
               return getErr(ErrCode.USER_ERROR_TELEXST);
            }
        } catch (Exception e){
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * @功能: 会员中心
     * @日期: liuwb on 2016-08-24 20:39 by create
     */
    @RequestMapping(value="/api/wx/user/members/center")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxUserMembersCenter() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel SRModel = this.getSRModel();
        try {
            SuperRecordModel wxInfo = (SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
            if(wxInfo != null){
                wxInfo.put("wx_open_id", wxInfo.getString("openid"));
                wxInfo.put("user_type", "5");
                SuperRecordModel userInfo = userService.findUserByOpenId(wxInfo);
                if(userInfo != null){//已经注册过
                    getSession().setAttribute(Comm.SESSION_USER,userInfo);
                    if(userInfo.getString("audit_flag").equals("2")){//已经审核过 进入会员中心
                        SRModel.put("userType",userInfo.getString("user_type"));// [5:服务商]
                        SRModel.put("promotionCode",userInfo.getString("promotion_code"));// [5:服务商]
                        int level = (Integer)userInfo.get("level");
                        SRModel.put("level",level);
                        SRModel.put("imgpath",userInfo.getString("imgpath"));
                        SRModel.put("nickname",userInfo.getString("nickname"));
                        SRModel.put("userId",userInfo.getString("sid"));
                        SRModel.put("rmoney","0.00");
                        if( level < 3 ){
                            userInfo.put("level_next",level+1);
                            userInfo.put("auditFlag","2");//必须是审核通过的
                            SRModel.put("count_num",userService.findCountMemberArea(userInfo));
                        } else {// 第四级服务商[镇/乡/街道]
                            /** 需审核数量**/
                            SuperRecordModel param = new SuperRecordModel();
                            param.put("user_pkey",userInfo.getString("sid"));
                            param.put("status_flag","1");//1：正常,有服务商.
                            param.put("audit_flag","0");// 0: 审核中
                            Long audit_count = teamMemberService.findServiceTeamMemberCount(param);
                            param.put("audit_flag","2");// 2: 全部审核通过
                            Long count_num = teamMemberService.findServiceTeamMemberCount(param);
                            SRModel.put("audit_count",audit_count.intValue());
                            SRModel.put("count_num",count_num.intValue());
                        }
                        SRModel.put("promotionCount", promotionService.findUserByPromotionCount(SRModel.getString("userId")));
//                        List<SuperRecordModel> yongchun = dataService.findListByCodeType("YONGCHUN");
//                        for(SuperRecordModel sl : yongchun){
//                            if(sl.getString("dataname").equals(SRModel.getString("userId")) ||
//                                    sl.getString("datavalue").equals(SRModel.getString("userId"))){
//                                SRModel.put("count_num","1000");//商家人数
//                                SRModel.put("promotionCount","5000");//分销人数
//                                SRModel.put("rmoney","158000.00");//账号金额
//                            }
//                        }
                        mv.addObject("srm",SRModel);
                        mv.setViewName("weixin/member_center");
                        return mv;
                    } else {
                        return apiWxLeagueMain();
                    }
                } else {
                        return apiWxLeagueMain();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        mv.setViewName("weixin/member_center");
        return mv;
    }

    /**
     * @功能: 团队成员 - 列表
     * @日期: liuwb on 2016-08-24 20:39 by create
     * @参数: user_id 用户id
     */
    @RequestMapping(value="/api/wx/user/members/list")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxUserStroeList() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel SRModel = this.getSRModel();
        try{
            SuperRecordModel userInfo = (SuperRecordModel)getSession().getAttribute(Comm.SESSION_USER);
            if(userInfo == null){//没有注册
                mv.setViewName("weixin/store_enter");
                return mv;
            }else{
                String userType = userInfo.getString("user_type");// [1:维修店] [5:服务商]
                int level = (Integer)userInfo.get("level");
                SRModel.put("userType",userType);
                SRModel.put("imgpath",userInfo.getString("imgpath"));
                List<SuperRecordModel> lists = new ArrayList<>();
                SRModel.put("userId",userInfo.getString("sid"));
                SRModel.put("level",level);
                SRModel.put("level_next",level + 1);
                SRModel.put("province",userInfo.get("province"));
                SRModel.put("city",userInfo.get("city"));
                SRModel.put("area",userInfo.get("area"));
                SRModel.put("town",userInfo.get("town"));
                SRModel.put("auditFlag","2");//审核通过
                if(level < 4){
                    if(level==1){
                        SRModel.put("groupParam","city");
                        SRModel.put("groupParamName","city_name");
                    }else if(level==2){
                        SRModel.put("groupParam","area");
                        SRModel.put("groupParamName","area_name");
                    }else if(level==3){
                        SRModel.put("groupParam","town");
                        SRModel.put("groupParamName","town_name");
                    }
                    lists = userService.findUsersByDistrict(SRModel);
                } else {
                    SRModel.put("groupParam","town");
                    SRModel.put("groupParamName","town_name");
                    SuperRecordModel srmParam = new SuperRecordModel();
                    srmParam.put("user_pkey",userInfo.getString("sid"));
                    srmParam.put("status_flag","1");//正常，有服务商
                    srmParam.put("audit_flag","2");//已经开店成功的维修店
                    lists = teamMemberService.findServiceTeamMember(srmParam);
                }
                for(SuperRecordModel s : lists){
                    s.put("nickname",s.getString("nickname"));
                    s.put("tel",s.getString("tel"));
                }
                mv.addObject("srm",SRModel);
                mv.addObject("lists",lists);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        mv.setViewName("weixin/member_list");
        return mv;
    }

    /**
     * @功能: 团队成员 - 详情信息
     * @日期: liuwb on 2016-08-24 20:39 by create
     * @参数: userId 用户id
     */
    @RequestMapping(value="/api/wx/user/members/detail")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxUserStroeDetail() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        mv.addObject("hostUser",promotionService.findHostUserInfo(srm.getString("userId")));//注意位置
        if("1".equals(srm.getString("userType"))){//维修店
            srm = userService.findUserAndStoreByUserId(srm.getString("userId"));
            mv.setViewName("weixin/member_store");
        }else if("5".equals(srm.getString("userType"))){//服务商
            srm = userService.findUserBySid(srm);
            mv.setViewName("weixin/member_service");
        }
        srm.put("nickname",StringUtils.repname(srm.getString("nickname")));
        srm.put("tel",StringUtils.repmobile(srm.getString("tel")));
        mv.addObject("srm",srm);
        return mv;
    }

    /**
     * @功能: 审核成员 - 列表
     * @日期: liuwb on 2016-08-24 20:39 by create
     */
    @RequestMapping(value="/api/wx/user/audit/list")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxUserAuditList(){
        SuperRecordModel paramSrm = this.getSRModel();
        ModelAndView mv = new ModelAndView();
        try{
            SuperRecordModel userInfo = (SuperRecordModel)getSession().getAttribute(Comm.SESSION_USER);
         /**   paramSrm.put("level",userInfo.get("level"));
            paramSrm.put("level_next",(Integer)userInfo.get("level") + 1);
            paramSrm.put("province",userInfo.get("province"));
            paramSrm.put("city",userInfo.get("city"));
            paramSrm.put("area",userInfo.get("area"));
            paramSrm.put("town",userInfo.get("town"));

            paramSrm.put("auditFlag","0");//未审核
            List<SuperRecordModel> un_audits = userService.findUsersByDistrict(paramSrm);
            mv.addObject("un_audits",un_audits);//未审核

            paramSrm.put("auditFlag","1");//更新中
            List<SuperRecordModel> in_audits = userService.findUsersByDistrict(paramSrm);
            mv.addObject("in_audits",in_audits);//更新中

            paramSrm.put("auditFlag","-N");//未通过 -1 or -2
            List<SuperRecordModel> no_audits = userService.findUsersByDistrict(paramSrm);
            mv.addObject("no_audits",no_audits);//未通过 **/
            SuperRecordModel srmParam = new SuperRecordModel();
            srmParam.put("user_pkey",userInfo.getString("sid"));
            srmParam.put("status_flag","1");//正常，有服务商

            srmParam.put("audit_flag","0");//维修店刚刚发起(0:等待服务商审核)
            List<SuperRecordModel> un_audits = teamMemberService.findServiceTeamMember(srmParam);
            mv.addObject("un_audits",un_audits);//未审核

            srmParam.put("audit_flag","1");//更新中
            List<SuperRecordModel> in_audits = teamMemberService.findServiceTeamMember(srmParam);
            mv.addObject("in_audits",in_audits);//更新中

            srmParam.put("audit_flag","-N");//未通过 -1 or -2
            List<SuperRecordModel> no_audits = teamMemberService.findServiceTeamMember(srmParam);
            mv.addObject("no_audits",no_audits);//未通过

            mv.addObject("srm",paramSrm);
        }catch (Exception e){
            e.printStackTrace();
        }
        mv.setViewName("weixin/audit_list");
        return mv;
    }

    /**
     * @功能: 审核成员 - 详情
     * @日期: liuwb on 2016-08-24 20:39 by create
     * @参数: user_id 用户主键信息
     */
    @RequestMapping(value="/api/wx/user/audit/detail")
    public ModelAndView apiWxUserAuditDetail(){
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        mv.addObject("hostUser",promotionService.findHostUserInfo(srm.getString("userId")));
        if("1".equals(srm.getString("userType"))){//维修店
            srm = userService.findUserAndStoreByUserId(srm.getString("userId"));
            mv.setViewName("weixin/audit_store");
        }else if("5".equals(srm.getString("userType"))){//服务商
            srm = userService.findUserBySid(srm);
            mv.setViewName("weixin/audit_service");
        }
        mv.addObject("srm", srm);
        return mv;
    }

    /**
     * @功能: 更新用户角色的表中的审核状态
     * @日期: liuwb on 2016-08-24 20:36 by create
     * @参数: userId M_USER sid 主键
     * @参数: auditFlag 需要更新的审核状态[0:未审核][1:服务商通过][-1:服务商拒绝][2:平台通过][-2:平台拒绝]
     * @参数: auditDescribe
     */
    @RequestMapping(value="/ajax/wx/audit/status")
    @ResponseBody
    @LoginAuth(isWx = true)
    public ResultModel ajaxWxAuditStatus() {
        SuperRecordModel SRModel = this.getSRModel();
        try {
            userService.updateUserAuditStatus(SRModel);
            String status = SRModel.getString("auditFlag");
            SuperRecordModel wxInfo =  (SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
            SuperRecordModel user = new SuperRecordModel() ;
            user = userService.findUserBySid(SRModel);
            Map wxAccessToken = getWxAccessToken();
            if(( status.equals("2") || status.equals("-2") ) && user.getString("user_type").equals("5")){//平台审核(服务商)
                 SendModelMsg.fwsjmModelMsg(user.getString("wx_open_id"),
                     wxAccessToken.get("access_token").toString(), status.equals("2"));
            } else if(( status.equals("1") || status.equals("-1") ) && user.getString("user_type").equals("1")){//服务商审核(维修店)
                 SendModelMsg.wxdsqModelMsg(user.getString("wx_open_id"),
                     wxAccessToken.get("access_token").toString(), status.equals("1"));
            } else if(( status.equals("2") || status.equals("-2") ) && user.getString("user_type").equals("1")){//平台商审核(维修店)
                 SendModelMsg.wxdsqPtModelMsg(user.getString("wx_open_id"),
                        wxAccessToken.get("access_token").toString(), status.equals("2"));
            }
            SuperRecordModel paramSrm = new SuperRecordModel();
            if("1".equals(status) ||  "-1".equals(status)){
                paramSrm.put("audit_fkey",SRModel.getString("userId"));
                paramSrm.put("audit_type","Service");
            } else if("2".equals(status) ||  "-2".equals(status)){
                paramSrm.put("audit_fkey",SRModel.getString("userId"));
                paramSrm.put("audit_type","Moto");
            }
            SuperRecordModel auditService = auditHistoryService.findHistoryByFkeyType(paramSrm);
            if(auditService != null){
                if(wxInfo!=null && "Moto".equals(auditService.getString("audit_type"))){
                    auditService.put("audit_user_id",wxInfo.getString("openid"));
                    auditService.put("audit_user_name",wxInfo.getString("nickname"));
                }
                auditService.put("audit_status",status);
                auditService.put("audit_describe",SRModel.getString("auditDescribe").trim());
                auditHistoryService.updateAuditStatusByid(auditService);
            }
            /** 更新审核描述 **/
            SuperRecordModel upUserSrm = new SuperRecordModel();
            upUserSrm.put("sid",SRModel.getString("userId"));
            if(!"".equals(SRModel.getString("auditDescribe").trim()) && ("-1".equals(status) || "-2".equals(status))){
                upUserSrm.put("audit_describe",SRModel.getString("auditDescribe"));
                userService.updateAuditDescribe(upUserSrm);
            }else if("1".equals(status)){//服务商审核通过
                upUserSrm.put("audit_describe",ErrCode.SERVICE_AUDIT_PASS);
                userService.updateAuditDescribe(upUserSrm);
            }else if("2".equals(status)){//平台审核通过
                upUserSrm.put("audit_describe",ErrCode.MOTO_AUDIT_PASS);
                userService.updateAuditDescribe(upUserSrm);
            }
            if("1".equals(user.getString("user_type")) && "2".equals(status)){//如果是维修店并且平台审核通过
                SuperRecordModel storeParam = new SuperRecordModel();
                storeParam.put("user_id",user.getString("sid"));//用户id
                storeParam.put("status","1");//0未审核 1审核通过 2审核未通过
                storeService.updateStoreStatus(storeParam);
            }
            return getSucceed(ErrCode.SUCCEED);
        } catch (Exception e){
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * @功能: 获取用户推广二维码
     */
    @RequestMapping(value="/api/wx/user/promotion")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxUserPromotion(){
        ModelAndView mv = new ModelAndView();
        SuperRecordModel wxInfo = (SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
        try {
            mv.addObject("ticket",getWxTicket().get("ticket"));
            if(wxInfo != null){
                wxInfo.put("wx_open_id", wxInfo.getString("openid"));
                wxInfo.put("user_type", "5");
                SuperRecordModel userInfo = userService.findUserByOpenId(wxInfo);
                if(userInfo!=null ){
                    if(userInfo.getString("audit_flag").equals("2")){
                        mv.addObject("promotionCode",userInfo.getString("promotion_code"));
                    }else{
                        return apiWxServiceLeague();
                    }
                } else {
                    wxInfo.put("wx_open_id", wxInfo.getString("openid"));
                    wxInfo.put("user_type", "1");
                    SuperRecordModel storeInfo = userService.findUserByOpenId(wxInfo);
                    if(storeInfo!=null && storeInfo.getString("audit_flag").equals("2")){
                        mv.addObject("promotionCode",storeInfo.getString("promotion_code"));
                    }else {
                        return apiWxLeagueMain();
                    }
                }
            }else{
                return apiWxLeagueMain();
            }
        }catch (Exception e){
            e.printStackTrace();
            mv.addObject("error_msg","请关闭微信重新打开!");
            mv.setViewName("error");
            return mv;
        }
        mv.addObject("wx_appid",Comm.APPID);
        mv.setViewName("weixin/promotionr");
        return mv;
    }

    /**
     * @功能: 分享 推广二维码
     */
    @RequestMapping(value="/api/wx/share/promotion")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxFxPromotion(){
        ModelAndView mv = new ModelAndView();
        SuperRecordModel SRModel = this.getSRModel();
        mv.addObject("promotionCode",SRModel.getString("promotionCode"));
        mv.setViewName("weixin/promotionr_share");
        return mv;
    }

    /**
     * @功能: 我要推广(新)
     * @日期: liuwb by 2016-09-12 14:28 on create
     */
    @RequestMapping(value="/api/wx/my/share")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxGeneralize(){
        ModelAndView mv = new ModelAndView();
        SuperRecordModel wxInfo = (SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
        try {
            mv.addObject("ticket",getWxTicket().get("ticket"));
            if(wxInfo != null){
                wxInfo.put("wx_open_id", wxInfo.getString("openid"));
                wxInfo.put("user_type", "5");
                SuperRecordModel userInfo = userService.findUserByOpenId(wxInfo);
                if(userInfo!=null ){
                    if(userInfo.getString("audit_flag").equals("2")){
                        mv.addObject("generInfo",userInfo);
                    }else{
                        return apiWxLeagueMain();
                    }
                } else {
                    wxInfo.put("wx_open_id", wxInfo.getString("openid"));
                    wxInfo.put("user_type", "1");
                    SuperRecordModel storeInfo = userService.findUserByOpenId(wxInfo);
                    if(storeInfo!=null && storeInfo.getString("audit_flag").equals("2")){
                        mv.addObject("generInfo",storeInfo);
                    }else {
                        return apiWxLeagueMain();
                    }
                }
            }else{
                return apiWxLeagueMain();
            }
        }catch (Exception e){
            e.printStackTrace();
            mv.addObject("error_msg","请关闭微信重新打开!");
            mv.setViewName("error");
            return mv;
        }
        mv.addObject("wx_appid",Comm.APPID);
        mv.setViewName("weixin/myshare");
        return mv;
    }

    /**
     * @功能: 推广 - 加盟入驻（新）
     * @日期: liuwb by 2016-09-12 20:14 on create
     */
    @RequestMapping(value="/api/wx/share/generalize")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxShareGeneralize(){
        ModelAndView mv = new ModelAndView();
        SuperRecordModel SRModel = this.getSRModel();
        String promotionCode = SRModel.getString("promotionCode");
        if(!"".equals(promotionCode)){
            mv.addObject("promotionCode",promotionCode);
            mv.addObject("proUserInfo",userService.findUserByPromotionCode(promotionCode));
        }
        mv.addObject("wx_appid",Comm.APPID);
        mv.addObject("ticket",getWxTicket().get("ticket"));
        mv.setViewName("weixin/generalize");
        return mv;
    }

    /**
     * @功能: ajax 获取推广码信息
     * @参数: promotionCode 推广码
     */
    @RequestMapping(value="/api/wx/promotion/info")
    @ResponseBody
    public ResultModel ajaxWxPromotionrInfo() {
        SuperRecordModel SRModel = this.getSRModel();
        try {
            if(!"".equals(SRModel.getString("promotionCode"))){
                SuperRecordModel promotionUserInfo =  userService.findUserByPromotionCode(SRModel.getString("promotionCode"));
                if(promotionUserInfo!=null){
                    SuperRecordModel promotion = new SuperRecordModel();
                    promotion.put("code",SRModel.getString("promotionCode"));
                    promotion.put("userType",promotionUserInfo.getString("user_type"));
                    promotion.put("serviceName",StringUtils.repname(promotionUserInfo.getString("nickname")));
                    promotion.put("serviceTel", StringUtils.repmobile(promotionUserInfo.getString("tel")));
                    return getSucceed(promotion);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return getErr(ErrCode.PROMOTION_CODE_INVALID);
    }

    /**
     * @功能:  查询团队成员 (原业务需求模块，现已停用)
     */
    @RequestMapping(value="/api/wx/search/member")
    @ResponseBody
    public ResultModel ajaxSearchParam(){
        SuperRecordModel SRModel = this.getSRModel();
        try {
            SuperRecordModel userInfo = (SuperRecordModel)getSession().getAttribute(Comm.SESSION_USER);
            SRModel.put("userId",userInfo.getString("sid"));
            List<SuperRecordModel> lists = userService.findUserByPromotion(SRModel);
            return  getSucceed(lists);
        } catch (Exception e){
            e.printStackTrace();
        }
        return getErr(ErrCode.ERROR_SYSTEM);
    }


}
